<template>
  <i-form
      ref="formRef"
      :model="formData"
      :rules="state.formRules"
      :label-width="80"
      label-position="right">

    <FormItem label="名称" prop="name">
      <Input v-model="formData.name" placeholder="请输入名称"/>
    </FormItem>
    <FormItem label="备注">
      <Input v-model="formData.depict" type="textarea" placeholder="请输入备注"/>
    </FormItem>
    <FormItem label="排序">
      <InputNumber v-model="formData.sort" controls-outside></InputNumber>
    </FormItem>

  </i-form>
</template>

<script setup>

import {getCurrentInstance, reactive, ref} from "vue";
import {RoleService} from "@/api/role";

const formData = reactive({
  // id
  id: '',
  // name
  name: '',
  // depict
  depict: '',
  // sort
  sort: 400
});

const state = reactive({
  formRules: {
    name: [{required: true, message: '名称不能为空!'}]
  }
});

const mode = ref('');

const {proxy} = getCurrentInstance();

const addRoleData = () => {
  proxy.$refs.formRef.validate(valid => {
    if (!valid) {
      Promise.reject();
      return false;
    } else {
      if (mode.value == 'add') {
        post();
      } else {
        edit();
      }
    }
  })
}

const post = async () => {
  const {data} = await RoleService.AddRole(formData);
  if (data.code === 200) {
    proxy.$Message.success({
      content: data.data,
      duration: 1.5,
      onClose: () => {
        window.location.reload();
      }
    })
  } else {
    proxy.$Message.error({
      content: data.data,
      duration: 1.5,
      onClose: () => {
        Promise.reject();
      }
    })
  }
}

const edit = async () => {
  const {data} = await RoleService.ModifyRole(formData);
  if(data.code === 200){
    proxy.$Message.success({
      content:data.data,
      duration:1.5,
      onClose:()=>{
        window.location.reload();
      }
    })
  }else{
    proxy.$Message.error({
      content:data.data,
      duration:1.5,
      onClose:()=>{
        Promise.reject();
      }
    })
  }
}

const setFormData = (data) => {
  Object.assign(formData, data);
}

const getDetail = async (e) => {
  let param = {id: e.id};
  const {data} = await RoleService.GetRoleById(param);
  if (data.code === 200) {
    setFormData(data.data)
  } else {
    proxy.$Message.error({
      content: data.data,
      duration: 1.5,
      onClose: () => {
        Promise.reject();
      }
    })
  }
}

defineExpose({
  mode,
  addRoleData,
  getDetail
})

</script>

<style scoped>

</style>
